<?php
class Session_Core {
	
	// session database
	private $sessionDatabase;
	// error message
	public $errorMessage;
	// user info
	public $userInfo = array();
	// user logged
	private $userLoggedIn;
	// user name
	private $userName;
	
	public function __construct(){
		$this->sessionDatabase = new UserSession_Driver();
		session_cache_expire(60 * 15);
		session_regenerate_id();	
	}
	
	public function isLoggedIn($username){
		if(isset($username) && ($username != "GUEST")){
			$userName = $_SESSION['user_name'];
			$this->userInfo = $this->getUserData($username);
			$_SESSION['access_level'] = $this->userInfo['access_level'];
		}
		else {
			$this->userInfo = $this->clearUserData();
		}
		$this->userInfo['userLoggedIn'] = $this->userLoggedIn;
		return $this->userInfo;
	}
	
	public function login($userName, $userPassword){
		if($this->sessionDatabase->checkUser($userName, $userPassword) == TRUE){
			$this->userInfo = $this->getUserData($userName);
			$_SESSION['user_name'] = $this->userInfo['username'];
		}
		else {
			$this->userInfo = $this->clearUserData();
		} 
		return $this->userInfo;
	}
	
	public function sessionDestroy($userInfo){
		session_destroy();
		$_SESSION['user_name'] = "GUEST";
		unset($userInfo);
		$this->userInfo = $this->clearUserData();
		return $this->userInfo;
	}
	
	private function getUserData($userName){
		$this->userInfo = $this->sessionDatabase->getUserInfo($userName);
		$_SESSION['user_name'] = $this->userInfo['username'];
		$this->userLoggedIn = TRUE;
		$this->userInfo['logged_in'] = $this->userLoggedIn;
		return $this->userInfo;
	}
	private function clearUserData(){
		$this->userLoggedIn = FALSE;
		$this->userInfo['access_level'] = 0;
		$_SESSION['user_name'] = "GUEST";
		$_SESSION['access_level'] = $this->userInfo['access_level'];
		$this->userInfo['userLoggedIn'] = $this->userLoggedIn;
		$this->userInfo['username'] = 'GUEST';
		return $this->userInfo;
	}
	
}